<template>
  <div>
    <!-- textContent存在就是普通文本，如果不存在就是下拉文本 -->
    <el-tooltip
      v-if="enableTooltip && showTitle"
      effect="dark"
      placement="top-start"
      :content="content"
    >
      <template v-if="isTag">
        <el-tag :type="tagType" class="tag-wrap" :style="`maxWidth: ${boxMaxWidth.val}${boxMaxWidth.unit}`">
          <slot name="label-tag"></slot>
          {{ content }}
        </el-tag>
      </template>
      <template v-else>
        <span class="content-span">{{ content }}</span>
      </template>
    </el-tooltip>
    <template v-else>
      <template v-if="isTag">
        <span ref="spanRef">
          <el-tag :type="tagType" class="tag-wrap" :style="`maxWidth: ${boxMaxWidth.val}${boxMaxWidth.unit}`">
            <slot name="label-tag"></slot>
            {{ content }}
          </el-tag>
        </span>
      </template>
      <template v-else>
        <span ref="spanRef" class="content-span">{{ content }}</span>
      </template>
    </template>
  </div>
</template>
<script>
export default {
  props: {
    textContent: { // 展示文本
      type: String | Number,
      default: ''
    },
    isTag: { // 是否以el-tag进行展示
      type: Boolean,
      default: false
    },
    tagType: {
      type: String,
      default: 'info'
    },
    enableTooltip: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      showTitle: false, // 是否显示toolTip
      boxMaxWidth: { val: 0, unit: '' }, // 容器最大宽度
    }
  },
  computed: {
    content () {
      return this.textContent + ''
    }
  },
  mounted () {
    this.initBoxWidth()
    this.$nextTick(() => {
      this.initShowTitle()
    })
  },
  updated () {
    this.initShowTitle()
  },
  methods: {
    // 初始化容器盒子最大宽度
    initBoxWidth () {
      const spanDom = this.$refs.spanRef // 文本内容
      this.boxMaxWidth = this.getComputedStyleMaxWidth(spanDom.parentNode)
    },
    // 初始化是否展示tooltip
    initShowTitle () {
      const spanDom = this.$refs.spanRef // 文本内容
      const parentDom = this.$refs.spanRef?.parentNode // 文本容器
      if (!parentDom) return
      const { val, unit } = this.getComputedStyleMaxWidth(parentDom)
      const percent = (spanDom.offsetWidth / parentDom.offsetWidth).toFixed(1) * 100
      const childWidth = unit == '%' ? percent : spanDom.offsetWidth
      this.showTitle = childWidth >= val
    },
    getComputedStyleMaxWidth (dom) {
      const maxWidthStyle = document.defaultView.getComputedStyle(dom, null).maxWidth ?? ''
      let unit = ''
      if (maxWidthStyle.indexOf('px') != -1) unit = 'px'
      if (maxWidthStyle.indexOf('%') != -1) unit = '%'
      const val = ~~maxWidthStyle.replace(unit, '')
      return { val, unit }
    }
  }
}
</script>
<style lang="less" scoped>
.tag-wrap {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.content-span {
  color: #85888e;
  font-size: 13px;
}
</style>
